/*
The following computer generated code depends upon concepts from other open source projects.
- FluentValidation - http://fluentvalidation.codeplex.com
- MyGeneration dOOdads - http://www.mygenerationsoftware.com

You will need to adjust this template for your application conventions.

*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FluentValidation;
using <%=@model_namespace%>;

namespace <%=@ui_namespace%>
{
    public partial class ucEditForm_<%= @table.TableName %> : System.Web.UI.UserControl
    {

        public event EventHandler RecordClosed;
        public event EventHandler RecordSaved;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnClose_Click(object sender, EventArgs e)
        {
            RaiseRecordClosedEvent();
        }

        public void RaiseRecordClosedEvent()
        {
            if (RecordClosed != null)
            {
                RecordClosed(this, new EventArgs());
            }
        }

        public void LoadRecord(decimal id)
        {
            blErrors.Items.Clear();
			<%= @table.TableName %> aRecord = new <%= @table.TableName %>();
            aRecord.LoadByPrimaryKey(id);
			<% for col in @table.Columns %>
            <%= col.ColumnName %>.Text = aRecord.<%= col.ColumnName %>.ToString();
			<% end %>
			
			lblInfoBar.Text = "Please update the following record.";
        }

        public void NewRecord()
        {
			<% for col in @table.Columns %>
			<% if col.ColumnName == "ID" %>
			<%= col.ColumnName %>.Text = "0";
			<% else %>
			<%= col.ColumnName %>.Text = "";
			<% end %>
			<% end %>
            
            lblInfoBar.Text = "Enter data for new record.";
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            saveRecord();
        }

        protected bool formIsOkay()
        {
            List<string> errors = new List<string>();
			<% for col in @table.Columns %>
            if(<%= col.ColumnName %>.Text.Trim().Length == 0)  errors.Add("<%= get_human_db_ref(col.ColumnName) %> is required.");
			<% end %>

            blErrors.Items.Clear();
            foreach (var error in errors)
            {
                blErrors.Items.Add(error);
            }

            return errors.Count == 0;
        }

		
        private bool saveRecord()
        {
            if (formIsOkay())
            {
                try
                {
                    var record = getRecordFromForm();
					record.Save();

                    RaiseRecordSaved();
                    LoadRecord(record.ID);
                    return true;
                }
                catch (FluentValidation.ValidationException ve)
                {
                    displayValidationErrors(ve);
                    return false;
                }catch(Exception ex)
				{
					blErrors.Items.Clear();
					blErrors.Items.Add(ex.Message);
					return false;
				}
            }
            else
            {

                return false;
            }
        }
		
        private void displayValidationErrors(ValidationException ve)
        {
            var errors = ve.Errors;
            blErrors.Items.Clear();
            foreach (var error in errors)
            {
                blErrors.Items.Add(error.ErrorMessage);
            }
        }
		

        private void RaiseRecordSaved()
        {
            if (RecordSaved != null)
            {
                RecordSaved(this, new EventArgs());
            }
        }

        private <%=@model_namespace%>.<%= @table.TableName %> getRecordFromForm()
        {
            <%=@model_namespace%>.<%= @table.TableName %> record = null;
            if (isNewRecord())
            {
				record = new <%=@model_namespace%>.<%= @table.TableName %>();
                record.AddNew();
            }
            else
            {
                decimal id = ConvertHelper.ParseDecimal(ID.Text);
				<%= @table.TableName %> t = new <%= @table.TableName %>();
				t.LoadByPrimaryKey(id);
				record = t;
            }

			<% for col in @table.Columns %>
			<% if col.ColumnName.to_s() =="CREATED_AT"  %>
			if(isNewRecord())
				record.CREATED_AT = DateTime.Now;
			<% elsif col.ColumnName.to_s() =="UPDATED_AT"  %>
			record.UPDATED_AT = DateTime.Now;				
			<% elsif col.DataType.to_s() == "System.Decimal" %>
			record.<%= col.ColumnName %> = ConvertHelper.ParseDecimal(<%= col.ColumnName %>.Text); //datatype: <%=col.DataType %>
			<% elsif col.DataType.to_s() == "System.Single" %>
			record.<%= col.ColumnName %> = ConvertHelper.ParseFloat(<%= col.ColumnName %>.Text); //datatype: <%=col.DataType %>			
			<% elsif col.DataType.to_s() == "System.Double" %>
			record.<%= col.ColumnName %> = ConvertHelper.ParseDouble(<%= col.ColumnName %>.Text); //datatype: <%=col.DataType %>			
			<% elsif col.DataType.to_s() == "System.Boolean" %>
			record.<%= col.ColumnName %> = <%= col.ColumnName %>.Text=="1";	//datatype: <%=col.DataType %>		
			<% elsif col.DataType.to_s() == "System.DateTime" %>
			record.<%= col.ColumnName %> = DateTime.Parse(<%= col.ColumnName %>.Text); //datatype: <%=col.DataType %>
			<% else %>
			record.<%= col.ColumnName %> = <%= col.ColumnName %>.Text; //datatype: <%=col.DataType %>
			<%end%>				
			<% end %>
	
            return record;
        }

        private bool isNewRecord()
        {
            return ID.Text == "0";
        }

        protected void btnSaveAndClose_Click(object sender, EventArgs e)
        {
            bool saveCompleted = saveRecord();
            if (saveCompleted)
            {
                RaiseRecordClosedEvent();
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (isNewRecord())
            {
                RaiseRecordClosedEvent();
            }
            else
            {
                <%= @table.TableName %> t = new <%= @table.TableName %>();
                t.LoadByPrimaryKey(ConvertHelper.ParseDecimal(ID.Text));
                t.MarkAsDeleted();
                t.Save();
				RaiseRecordClosedEvent();
            }
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            NewRecord();
        }
    }
}